package cn.otrue.patienthealthmanager.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.DoctorParticularsActivity;
import cn.otrue.patienthealthmanager.adapter.FindDoctorPrivateFragmentAdpater;
import cn.otrue.patienthealthmanager.bean.DoctorBaseinfo;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.XListView;
import cn.otrue.patienthealthmanager.view.XListView.IXListViewListener;
import cn.otrue.patienthealthmanager.xmpp.XmppTool;

import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;

/**
 * 找医生->私人医生
 * 
 * @author G
 * 
 */
public class FindDoctorPrivateFragment extends BaseFragment implements
		OnTouchListener, IXListViewListener {
	private List<DoctorBaseinfo> siren = new ArrayList<DoctorBaseinfo>();

	// private TextView tv_attention_dactor;
	private View rootView;
	private int currentPage = 1;
	private XListView lv_doctor_private;
	private FindDoctorPrivateFragmentAdpater adapter;
	private Handler handler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			onLoad();
			if (state.equals("001")) {

				String dataStr = data.getString("data");
				List<DoctorBaseinfo> newList = HttpServer.gson.fromJson(
						dataStr, new TypeToken<List<DoctorBaseinfo>>() {
						}.getType());
				CommonUtil.listRemoveNull(newList);

				siren.addAll(newList);
				if (siren.size() > 5) {

					lv_doctor_private.setPullLoadEnable(true);
				}
				adapter = new FindDoctorPrivateFragmentAdpater(
						rootView.getContext(), siren);
				lv_doctor_private.setAdapter(adapter);

				if (siren != null && siren.size() > 0) {

					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								List<DoctorBaseinfo> dbData = db
										.findAll(Selector.from(
												DoctorBaseinfo.class).where(
												"mId", "=",
												MyConst.getACCOUNT()));
								if (dbData != null && dbData.size() > 0) {
									for (int i = 0; i < siren.size(); i++) {
										DoctorBaseinfo doctor = db
												.findFirst(Selector
														.from(DoctorBaseinfo.class)
														.where("aliasAccount",
																"=",
																siren.get(i)
																		.getAliasAccount())
														.and(WhereBuilder
																.b("mId",
																		"=",
																		MyConst.getACCOUNT())));
										if (doctor != null) {
											db.delete(doctor);

										} else {

										}
										siren.get(i).setmId(
												MyConst.getACCOUNT());
										siren.get(i).setmJid(XmppTool.USERJID);
										db.save(siren.get(i));

									}
								} else {
									for (int i = 0; i < siren.size(); i++) {
										siren.get(i).setmId(
												MyConst.getACCOUNT());
										siren.get(i).setmJid(XmppTool.USERJID);
									}
									db.saveAll(siren);
								}
							} catch (Exception e) {

							}
						}
					}).start();

				}
			} else {
				onLoad();
			}

		}

		@Override
		public void onFail(Bundle data, String state) {

			onLoad();
		}

	};

	private DbUtils db;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		db = DbUtils.create(this.getActivity());
		rootView = inflater.inflate(R.layout.fragment_doctor_private, null);
		initView(rootView);

		return rootView;
	}

	private void initView(final View rootView) {

		lv_doctor_private = (XListView) rootView
				.findViewById(R.id.lv_doctor_private);
		lv_doctor_private.setPullLoadEnable(false); // 是否开启上拉加载
		lv_doctor_private.setXListViewListener(this);// 上啦加载和下拉刷新的监听
		lv_doctor_private.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				Intent intent = new Intent();
				intent.putExtra("aliasAccount", siren.get(arg2 - 1)
						.getAliasAccount());
				intent.putExtra("jid", siren.get(arg2 - 1).getJid());
				intent.putExtra("isAttention", siren.get(arg2 - 1)
						.getIsAttention());
				intent.setClass(rootView.getContext(),
						DoctorParticularsActivity.class);
				startActivity(intent);

			}
		});
		adapter = new FindDoctorPrivateFragmentAdpater(rootView.getContext(),
				siren);
		lv_doctor_private.setAdapter(adapter);
		this.isInitViewCompleted = true;
	}

	private void onLoad() {
		lv_doctor_private.stopRefresh();
		lv_doctor_private.stopLoadMore();
		lv_doctor_private.setRefreshTime("刚刚");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		lv_doctor_private.setPullLoadEnable(false);
		siren.clear();
		getData(currentPage);

		super.onResume();
	}

	private void getData(int i) {
		siren = new ArrayList<DoctorBaseinfo>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("sender", MyConst.getACCOUNT());
		map.put("isPrivateDoctor", 1);

		TransferParameter parameter = new TransferParameter();
		parameter.setPagesize("20");
		parameter.setCurrentPage(i + "");
		parameter.setData(map);
		new HttpServer()
				.post(HttpCons.QUERY_ATTENTION_INFO, parameter, handler);

	}

	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	public static Fragment newInstance() {
		return new FindDoctorPrivateFragment();
	}

	@Override
	public String setPageName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
			siren.clear();
			adapter.notifyDataSetChanged();
			currentPage = 1;

			getData(currentPage);
		} else {
			siren.clear();
			adapter.notifyDataSetChanged();
			onLoad();
		}
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
			currentPage++;
			getData(currentPage);
		} else {
			siren.clear();
			adapter.notifyDataSetChanged();
			onLoad();
		}
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			// 相当于Fragment的onResume
			if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
				if (isInitViewCompleted) {
					siren.clear();
					adapter.notifyDataSetChanged();
					currentPage = 1;
					getData(currentPage);

				}
			}
			siren.clear();
			adapter.notifyDataSetChanged();
		} else {
			// 相当于Fragment的onPause

		}
	}

}
